#pragma once
#include <iostream>
#include <string>
#include <ctime>
#include <cassert>
#include <unistd.h>
#include "Socket.hpp"
#include "Protocol.hpp"
static void Usage(const std::string &proc)
{
    std::cout << "\nUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

 const std::string opers = "+-*/%";


int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    //创建套接字
    Sock client_sock;
    client_sock.Socket();
    int sockfd=client_sock.get_sockfd();
    //2.绑定，我们自己不要手动绑定，一般由OS自由随机选择！
    //3.链接
    bool ret=client_sock.Connect(serverip,serverport);
    if(ret==false)
    {
        lg(Fatal,"Connect error ");
        return -1;
    }

    //通信
    //char buffer[1024];
    srand(0^12);
    int cnt=0;
    string recieve_package;
    while(cnt <= 10)
    {
        std::cout << "===============第" << cnt << "次测试....., " << "===============" << std::endl;
        //准备数据
        int x=rand()%30;
        //usleep(1234);
        int y=rand()%30;
        //usleep(1234);
         //printf("error5     ;;;;;;;\n");
        char op=opers[rand()%opers.size()];
        //printf("error1  X %d,Y %d   ;;;;;;;\n",x,y);
        Sequent request(x,op,y);
        std::string content;
        std::string package;
        request.Serialize(content);
         //printf("error2   content::: %s ;;;;;;;\n",content.c_str());
        package=Encode(content);
        //printf("error 3  package:%s  ;;;;;;;\n",package.c_str(),package.size());
        //buffer=package.c_str();
        //写数据
        int RET=write(sockfd,package.c_str(),package.size());
        if(RET<0)
            printf("error 4    ;;;;;;;\n");
        //读数据
        char read_buffer[1024];
        std::string content2;
        Response response;
        
        int n=read(sockfd,read_buffer,sizeof(read_buffer));
        read_buffer[n]=0;
       // printf("read_buffer : %s \n",read_buffer);
        if(n>0)
        {
            read_buffer[n]=0;
            
            recieve_package+=read_buffer;

            //解包
            bool r1=Decode(recieve_package,content2);
            if(r1==false) assert(r1); 
            //反序列化
            bool r=response.Deserialize(content2);
            if(r==false) assert(r); 

            //得出结果
            response.DebugPrint();
            
        }
        std::cout<<".........................."<<std::endl;
        cnt++;
        sleep(1);
    }

    //printf("-------------------");
    close(sockfd);



    return 0;
}